package instantHelper.ClosedMode;

import instantHelper.Models.CustomHttpClient;
import instantHelper.NormalMode.MyLocationListener;
import instantHelper.Raceway.Contact;
import instantHelper.Raceway.DbHelper;
import instantHelper.Raceway.FTPHelper;
import instantHelper.Raceway.InstantHelperConstant;
import instantHelper.Raceway.Person;
import instantHelper.Raceway.R;
import instantHelper.Raceway.R.id;
import instantHelper.Raceway.R.layout;
import instantHelper.Raceway.SettingsUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.graphics.Bitmap.CompressFormat;
import android.hardware.Camera;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.text.method.DateTimeKeyListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;

public class ClosedModePictureCapture extends Activity implements
		SurfaceHolder.Callback, OnClickListener {
	static final int FOTO_MODE = 0;
	private static final String TAG = ClosedModePictureCapture.class.getSimpleName();
	Camera mCamera;
	boolean mPreviewRunning = false;
	private Context mContext = this;
	String requestId = "";
	int counter = 0;
	String androidId = "";

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		Log.e(TAG, "onCreate");
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			requestId = extras.getString("requestId");
		}
		androidId = SettingsUtil.getAndroidID(getApplicationContext());

		MyLocationListener.getGPSData(getApplicationContext(), androidId,
				requestId);
		getWindow().setFormat(PixelFormat.TRANSLUCENT);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.normalmode_picture);

		mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
		// mSurfaceView.setOnClickListener(this);
		mSurfaceHolder = mSurfaceView.getHolder();
		mSurfaceHolder.addCallback(this);
		mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

	Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
		public void onPictureTaken(byte[] imageData, Camera c) {
			if (imageData != null) {
				Intent mIntent = new Intent();
				String pictureQuality = SettingsUtil
						.getPictureQuality(getApplicationContext());
				int quality = 30;
				if (pictureQuality.equals("Low")) {
					quality = 30;
				} else if (pictureQuality.equals("Medium")) {
					quality = 65;
				} else if (pictureQuality.equals("High")) {
					quality = 100;
				}
				StoreByteImage(mContext, imageData, quality, "ImageName");
				mCamera.startPreview();
				setResult(FOTO_MODE, mIntent);
				finish();
			}
		}
	};

	protected void onResume() {
		Log.e(TAG, "onResume");
		super.onResume();
	}

	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	protected void onStop() {
		Log.e(TAG, "onStop");
		super.onStop();
	}

	public void surfaceCreated(SurfaceHolder holder) {
		Log.e(TAG, "surfaceCreated");
		try {
			mCamera = Camera.open();
			takePictures(holder);
			mPreviewRunning = true;
		} catch (Exception e) {
			mCamera.release();
		}
	}

	public void takePictures(SurfaceHolder holder) {
		for (int i = 0; i < 5; i++) {
			try {
				// mCamera.setPreviewDisplay(holder);
				mCamera.startPreview();
				mCamera.takePicture(null, mPictureCallback, mPictureCallback);
				mCamera.stopPreview();
				Thread.sleep(5000);
			} catch (Exception e) {
			}
		}
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
		Log.e(TAG, "surfaceChanged");

		// XXX stopPreview() will crash if preview is not running
		if (mPreviewRunning) {
			mCamera.stopPreview();
		}

		// Camera.Parameters p = mCamera.getParameters();
		// p.setPreviewSize(w, h);
		// mCamera.setParameters(p);
		try {
			mCamera.setPreviewDisplay(holder);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// mCamera.startPreview();
		mPreviewRunning = true;
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		Log.e(TAG, "surfaceDestroyed");
		mCamera.stopPreview();
		mPreviewRunning = false;
		mCamera.release();
	}

	private SurfaceView mSurfaceView;
	private SurfaceHolder mSurfaceHolder;

	public void onClick(View arg0) {
		mCamera.takePicture(null, mPictureCallback, mPictureCallback);
	}

	public boolean StoreByteImage(Context mContext, byte[] imageData,
			int quality, String expName) {

		File sdImageMainDirectory = new File("/sdcard");
		FileOutputStream fileOutputStream = null;
		try {

			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 5;
			Bitmap myImage = BitmapFactory.decodeByteArray(imageData, 0,
					imageData.length, options);
			String fileName = createPicturePaths("picture_" + requestId + "_"
					+ counter + ".jpg");
			fileOutputStream = new FileOutputStream(fileName);

			BufferedOutputStream bos = new BufferedOutputStream(
					fileOutputStream);
			myImage.compress(CompressFormat.JPEG, quality, bos);
			bos.flush();
			bos.close();

			String result = sendHelpRequestPicture("picture_" + requestId + "_"
					+ counter + ".jpg", requestId);
			if (result.equals("successfull")) {

				boolean issend = FTPHelper.sendToServer(fileName, "pictures/");
				if (!issend) {
					insertDirectoryTable("picture_" + requestId + "_" + counter
							+ ".jpg", false);
				} else {
					if (SettingsUtil
							.getDeleteDataControl(getApplicationContext())) {
						SettingsUtil.deleteFile(fileName);
					}
				}
			}
			counter++;

		} catch (Exception e) {
			e.printStackTrace();
		}

		return true;
	}

	private void insertDirectoryTable(String path, boolean issend) {
		ContentValues contentValues = new ContentValues();
		contentValues.put(InstantHelperConstant.DB_DIRECTORY_PATH, path);
		contentValues.put(InstantHelperConstant.DB_DIRECTORY_REQUEST_ID,
				requestId);
		contentValues.put(InstantHelperConstant.DB_DIRECTORY_ISSEND, issend);
		contentValues.put(InstantHelperConstant.DB_DIRECTORY_TYPE, "picture");
		Date date = new Date();
		contentValues.put(InstantHelperConstant.DB_DIRECTORY_DATE,
				date.toString());

		DbHelper myDbHelper = new DbHelper(ClosedModePictureCapture.this);
		SQLiteDatabase db = myDbHelper.getWritableDatabase();

		try {
			db.insertOrThrow(InstantHelperConstant.DB_DIRECTORY_TABLE, null,
					contentValues);

		} catch (Exception e) {
		}
	}

	private String sendHelpRequestPicture(String picturePath, String requesId) {
		String url = InstantHelperConstant.CentralAppURL
				+ "/androidhelprequest/newPicture";

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("requestId", requesId));
		postParameters.add(new BasicNameValuePair("picturePath", picturePath));
		postParameters.add(new BasicNameValuePair("androidId", androidId));
		String response = null;
		String result = "";
		try {
			response = CustomHttpClient.executeHttpPost(url, postParameters);
			String res = response.toString();
			JSONObject jObject = new JSONObject(res);
			result = jObject.getString("result");
		} catch (Exception e) {
		}
		return result;
	}

	protected String createPicturePaths(String filePath) {
		String fileName = "ihcenterapp/pictures/" + filePath;
		fileName = sanitizePath(fileName);
		// make sure the directory we plan to store the recording in exists
		File directory = new File(fileName).getParentFile();
		if (!directory.exists() && !directory.mkdirs()) {
			try {
				throw new IOException("Path to file could not be created.");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return fileName;
	}

	protected String sanitizePath(String path) {
		if (!path.startsWith("/")) {
			path = "/" + path;
		}
		if (!path.contains(".")) {
			path += ".jpg";
		}
		return Environment.getExternalStorageDirectory().getAbsolutePath()
				+ path;
	}

}